package com.rc.saas.tenant.controller.car;

import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageInfo;
import com.rc.saas.tenant.base.TenantBaseController;
import com.rc.saas.tenant.base.WebPageInfo;
import com.rc.saas.tenant.common.vo.TResponse;
import com.rc.saas.tenant.component.UploadComponent;
import com.rc.saas.tenant.component.UploadImg;
import com.rc.saas.tenant.model.car.TenantCarNumber;
import com.rc.saas.tenant.model.fault.RcElecPileFaultRecord;
import com.rc.saas.tenant.model.platform.PlatformCarBrand;
import com.rc.saas.tenant.model.tenant.Tenant;
import com.rc.saas.tenant.model.tenant.TenantUser;
import com.rc.saas.tenant.search.car.CarNumberSearch;
import com.rc.saas.tenant.search.fault.RcElecPileFaultRecordSearch;
import com.rc.saas.tenant.search.platform.PlatformCarBrandSearch;
import com.rc.saas.tenant.service.car.TenantCarNumberService;
import com.rc.saas.tenant.service.platform.PlatformCarBrandService;
import com.rc.saas.tenant.service.tenant.TenantService;
import com.rc.saas.tenant.shiro.ShiroUtils;
import com.rc.saas.tenant.util.ExportUtils;
import com.rc.saas.tenant.vo.car.TenantCarNumberVo;
import com.rc.saas.tenant.vo.platform.PlatformCarBrandVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.Date;

/**
 * @author zhoushiyu
 * @create 2021/5/22
 */
@Controller
@RequestMapping("/platformCarBrand")
public class PlatformCarBrandController extends TenantBaseController {
    private final Logger logger = LoggerFactory.getLogger(PlatformCarBrandController.class);

    @Autowired
    private UploadImg uploadImg;

    @Autowired
    private TenantService tenantService;

    @Autowired
    private PlatformCarBrandService platformCarBrandService;

    @Autowired
    private UploadComponent uploadComponent;

    /**
     * 跳转 车牌品牌列表
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index() {
        return "/templates/platform/platformCarBrand";
    }

    /**
     * 跳转 车牌品牌新增页面
     */
    @RequestMapping(value = "/addCarBrand", method = RequestMethod.GET)
    public String addPlatformCarBrand() {
        return "/templates/platform/addPlatformCarBrand";
    }

    /**
     * 跳转 车牌品牌编辑页面
     */
    @RequestMapping(value = "/editCarBrand/{brandId}", method = RequestMethod.GET)
    public String editPlatformCarBrand(Model model, @PathVariable("brandId") Long brandId) {
        PlatformCarBrand platformCarBrand = platformCarBrandService.selectByPrimaryKey(brandId);
        model.addAttribute("platformCarBrand", platformCarBrand);
        return "/templates/platform/editPlatformCarBrand";
    }


    /**
     * 车辆品牌分页数据
     */
    @ResponseBody
    @RequestMapping(value = "/listPageCarBrand", method = RequestMethod.GET)
    public WebPageInfo listPageCarBrand(PlatformCarBrandSearch PlatformCarBrandSearch) {
        PageInfo<PlatformCarBrand> pageInfo = platformCarBrandService.listPageByCondition(PlatformCarBrandSearch);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }
    /**
     * 删除车辆品牌
     *
     * @return
     */
    @RequestMapping(value = "/deleteCarBrand", method = RequestMethod.POST)
    @ResponseBody
    public TResponse deleteCarBrand(Long brandId) {
        PlatformCarBrand info = platformCarBrandService.selectByPrimaryKey(brandId);
        if (info==null){
            return TResponse.FAIL("请求错误");
        }
        platformCarBrandService.deleteByPrimaryKey(brandId);
        return TResponse.SUCCESS();
    }

    /**
     * 保存车牌库
     */
    @ResponseBody
    @RequestMapping(value = "/saveOrUpdateCarBrand", method = RequestMethod.POST)
    public TResponse saveOrUpdateCarBrand(PlatformCarBrand platformCarBrand, @RequestParam(value = "file1", required = false) MultipartFile file1) {

        TenantUser user = ShiroUtils.getSessionUser();

        Tenant tenant = tenantService.selectByTenantCode(user.getTenantCode());

        try {
            PlatformCarBrand info = platformCarBrandService.selectByPrimaryKey(platformCarBrand.getBrandId());
           /* if (file1.getSize() != 0) {
                TResponse tResponse = uploadImg.uploadImg(user.getTenantCode(), file1);
                if (tResponse.getStatus() == 200) {
                    if (info!=null){
                        info.setBrandImg(platformCarBrand.getBrandImg());
                    }else{
                        platformCarBrand.setBrandImg((String) tResponse.getData());
                    }

                } else {
                    return tResponse;
                }
            }*/
            if (file1 != null && file1.getSize() != 0 && file1.getContentType().contains("image")) {
                String imgUrl = uploadComponent.uploadFile(user.getTenantCode(), file1);
                if (info!=null){
                    info.setBrandImg(imgUrl);
                }else{
                    platformCarBrand.setBrandImg(imgUrl);
                }
            }
            /*if (file1 != null && file1.getSize() != 0 && file1.getContentType().contains("image")) {
                String imgUrl = uploadComponent.uploadFile(user.getTenantCode(), file1);
                info.setQrcodeImg(imgUrl);
            }
            customerSerService.updateByPrimaryKey(info);*/
            if (info!=null){
                info.setBrandName(platformCarBrand.getBrandName());
                info.setSort(platformCarBrand.getSort());
                info.setStatus(platformCarBrand.getStatus());
                platformCarBrandService.updateByPrimaryKey(info);
            }else{

                platformCarBrand.setCreatedBy(user.getLoginName());
                platformCarBrand.setCreatedTime(new Date());
                platformCarBrand.setLastUpdatedBy(user.getLoginName());
                platformCarBrand.setLastUpdatedTime(new Date());
                platformCarBrandService.insert(platformCarBrand);
            }
            return TResponse.SUCCESS();
        }catch (Exception e){
            logger.error("保存标签失败", e);
            return TResponse.FAIL("保存标签失败");
        }

    }

    /**
     * 导出品牌列表数据
     */
    @ResponseBody
    @RequestMapping("/exporListPageCarBrand")
    public TResponse exporListPageCarBrand(PlatformCarBrandSearch search, HttpServletResponse response) {
        response.setHeader("Set-Cookie", "fileDownload=true; path=/");
        //导出拼接开始条数
        try {
            ExportUtils.setDefaultPaging(search);
            PageInfo<PlatformCarBrand> pageInfo = platformCarBrandService.listPageByCondition(search);
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("品牌列表列表", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), PlatformCarBrand.class).sheet("品牌列表列表").doWrite(pageInfo.getList());
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("导出失败", e.getMessage());
            return TResponse.FAIL(e.getMessage());
        }
    }

}
